﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SPServerName.ControlTemplates.SPServerName
{
    public partial class SPServerName : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (IsFarmAdmin() || ServerParamIsSet())
                {
                    this.lblServerName.Width = new Unit("100%");
                    this.lblServerName.Text = string.Format("{0}", Page.Server.MachineName);
                }
            }
            catch { }
        }


        bool IsFarmAdmin()
        {
            string loginName = SPContext.Current.Web.CurrentUser.LoginName;
            bool isFarmAdmin = false;
            try
            {
                if (SPFarm.Local.CurrentUserIsAdministrator(true))
                {
                    isFarmAdmin = true;
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }

            return isFarmAdmin;
        }

        bool ServerParamIsSet()
        {
            bool hasServerParam = false;
            try
            {
                string requestParamShowServer = (string)Request.Params["SHOWSERVER"];
                if (requestParamShowServer != null)
                {
                    int result = 0;
                    if (Int32.TryParse(requestParamShowServer, out result))
                    {
                        if (result == 1)
                        {
                            hasServerParam = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }

            return hasServerParam;
        }
    }

}
